﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Reflection;
using landlord2.Properties;

namespace landlord2
{
    /// <summary>
    /// TableWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TableWindow : Window
    {
        private DispatcherTimer m_timer;
        private DataSet m_dsTables;

        public TableWindow()
        {
            InitializeComponent();

            m_timer = new DispatcherTimer();
            m_timer.Tick += Timer_Tick;
            m_timer.Interval = TimeSpan.FromSeconds(2);

            cmbIP.Items.Clear();
            int i = 1;
            while (true)
            {
                string ip = GetServerIP(i);
                if (string.IsNullOrEmpty(ip)) break;
                cmbIP.Items.Add(ip);
                i++;
            }
            cmbIP.Text = Settings.Default.ServerIP;
            txtName.Text = Settings.Default.PlayerName;
            cmbGender.SelectedIndex = Settings.Default.PlayerGender;
        }

        private string GetServerIP(int index)
        {
            Type type = Settings.Default.GetType();
            string name = "ServerIP" + index.ToString();
            PropertyInfo pi = type.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
            if (pi == null) return null;
            return (string)pi.GetValue(Settings.Default, null);
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            if (GameClient.Current.Client != null) GameClient.Current.Client.HeartBeat();
        }

        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(cmbIP.Text)) throw new Exception("请输入服务器地址！");
                if (string.IsNullOrEmpty(txtName.Text)) throw new Exception("请输入玩家名字！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            GameClient.CreateInstance(cmbIP.Text, Settings.Default.ServerPort);
            GameClient.Current.Name = txtName.Text;
            GameClient.Current.Gender = cmbGender.SelectedIndex;

            Settings.Default.ServerIP = cmbIP.Text;
            Settings.Default.PlayerName = txtName.Text;
            Settings.Default.PlayerGender = cmbGender.SelectedIndex;
            Settings.Default.Save();

            try
            {
                GameClient.Current.Client.Regist(GameClient.Current.Guid, GameClient.Current.Name, GameClient.Current.Gender);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "连接失败", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            m_timer.Start();
            GameClient.Current.OnTableList += OnTableList;
            GameClient.Current.OnOpenMainWindow += OnOpenMainWindow;
            btnConnect.IsEnabled = false;
            cmbIP.IsEnabled = false;
            txtName.IsEnabled = false;
            cmbGender.IsEnabled = false;
            OnTableList(GameClient.Current.Client.GetTableList());
        }

        private void OnTableList(DataSet ds)
        {
            ds.Tables[0].Columns.Add("StatusString", typeof(string));
            ds.Tables[0].Columns.Add("Players", typeof(string));
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                switch (Convert.ToInt32(row["Status"]))
                {
                    case 0:
                        row["StatusString"] = "未开始";
                        break;
                    case 1:
                        row["StatusString"] = "已开始";
                        break;
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < 4; i++)
                {
                    string field = "Player" + (i + 1).ToString();
                    if (row.IsNull(field)) continue;
                    if (sb.Length > 0) sb.Append(", ");
                    sb.Append(row[field].ToString());
                }
                row["Players"] = sb.ToString();
            }
            m_dsTables = ds;

            Dispatcher.BeginInvoke((Action)delegate()
            {
                int index = lvwTables.SelectedIndex;
                lvwTables.ItemsSource = ds.Tables[0].DefaultView;
                lvwTables.SelectedIndex = index;
            });
        }

        private void lvwTables_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ShowSeats(lvwTables.SelectedIndex);
        }

        private void ShowSeats(int table)
        {
            if (lvwTables.SelectedIndex >= 0)
            {
                DataRow row = m_dsTables.Tables[0].Rows[table];
                btnSeat1.Content = row.IsNull("Player1") ? "空" : row["Player1"].ToString();
                btnSeat2.Content = row.IsNull("Player2") ? "空" : row["Player2"].ToString();
                btnSeat3.Content = row.IsNull("Player3") ? "空" : row["Player3"].ToString();
                btnSeat4.Content = row.IsNull("Player4") ? "空" : row["Player4"].ToString();
                btnSeat1.IsEnabled = true;
                btnSeat2.IsEnabled = true;
                btnSeat3.IsEnabled = true;
                btnSeat4.IsEnabled = true;
            }
            else
            {
                btnSeat1.IsEnabled = false;
                btnSeat2.IsEnabled = false;
                btnSeat3.IsEnabled = false;
                btnSeat4.IsEnabled = false;
            }
        }

        private void btnSeat_Click(object sender, RoutedEventArgs e)
        {
            int table = lvwTables.SelectedIndex;
            int seat;
            if (sender == btnSeat1) seat = 0;
            else if (sender == btnSeat2) seat = 1;
            else if (sender == btnSeat3) seat = 2;
            else seat = 3;

            DataSet ds;
            if (GameClient.Current.Table == table && GameClient.Current.Seat == seat)
            {
                ds = GameClient.Current.Client.ClearSeat();
                if (ds != null)
                {
                    GameClient.Current.Table = null;
                    GameClient.Current.Seat = null;
                    OnTableList(ds);
                }
            }
            else
            {
                ds = GameClient.Current.Client.SetSeat(lvwTables.SelectedIndex, seat);
                if (ds != null)
                {
                    GameClient.Current.Table = lvwTables.SelectedIndex;
                    GameClient.Current.Seat = seat;
                    OnTableList(ds);
                }
            }
        }

        private void OnOpenMainWindow()
        {
            Dispatcher.BeginInvoke((Action)delegate()
            {
                GameClient.Current.OnTableList -= OnTableList;
                GameClient.Current.OnOpenMainWindow -= OnOpenMainWindow;
                DialogResult = true;
            });
        }
    }
}
